package com.example.xinlijiankangsys.controller;

import com.example.xinlijiankangsys.pojo.QuestionnaireRecord;
import com.example.xinlijiankangsys.pojo.Result;
import com.example.xinlijiankangsys.service.QuestionnaireService;
import com.example.xinlijiankangsys.util.ReturnResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/questionnaire")
public class QuestionnaireController {

    private static final Logger log = LoggerFactory.getLogger(QuestionnaireController.class);
    @Autowired
    private QuestionnaireService questionnaireService;

    /**
     * 提交问卷记录（自动处理新增或更新）
     */
    @PostMapping("/records")
    public Result saveRecord(@RequestBody QuestionnaireRecord record) {
        if(record.getUserId()==null)return ReturnResultUtil.failure("用户非法");
        boolean success = questionnaireService.saveQuestionnaireRecord(record);
        return success ? ReturnResultUtil.success() :
                ReturnResultUtil.failure("问卷提交失败");
    }

    /**
     * 批量提交问卷记录
     */
    @PostMapping("/records/batch")
    public Result batchSaveRecords(@RequestBody List<QuestionnaireRecord> records) {
        try {
            boolean success = questionnaireService.batchSaveRecords(records);
            return success ? ReturnResultUtil.success() :
                    ReturnResultUtil.failure("批量提交失败");
        } catch (Exception e) {
            return ReturnResultUtil.failure("批量处理异常: " + e.getMessage());
        }
    }

    /**
     * 获取特定问卷记录
     */
    @GetMapping("/records/{questionnaireId}/{userId}")
    public Result getRecord(
            @PathVariable int questionnaireId,
            @PathVariable int userId) {
        QuestionnaireRecord record = questionnaireService.getRecord(questionnaireId, userId);
        return record != null ? ReturnResultUtil.success(record) :
                ReturnResultUtil.failure("记录不存在");
    }

    /**
     * 获取用户所有问卷记录
     */
    @GetMapping("/records/user/{userId}")
    public Result getUserRecords(@PathVariable String userId) {
        List<QuestionnaireRecord> records = questionnaireService.getUserRecords(userId);
        return ReturnResultUtil.success(records);
    }

    /**
     * 获取问卷所有用户记录
     */
    @GetMapping("/records/questionnaire/{questionnaireId}")
    public Result getQuestionnaireRecords(@PathVariable int questionnaireId) {
        List<QuestionnaireRecord> records = questionnaireService.getQuestionnaireRecords(questionnaireId);
        return ReturnResultUtil.success(records);
    }

    /**
     * 删除问卷记录
     */
    @DeleteMapping("/records/{questionnaireId}/{userId}")
    public Result deleteRecord(
            @PathVariable int questionnaireId,
            @PathVariable String userId) {
        boolean success = questionnaireService.deleteRecord(questionnaireId, userId);
        return success ? ReturnResultUtil.success() :
                ReturnResultUtil.failure("删除失败");
    }

    /**
     * 获取用户问卷得分
     */
    @GetMapping("/score/{questionnaireId}/{userId}")
    public Result getUserScore(
            @PathVariable int questionnaireId,
            @PathVariable String userId) {
        Integer score = questionnaireService.getUserQuestionnaireScore(questionnaireId, userId);
        return score != null ? ReturnResultUtil.success(score) :
                ReturnResultUtil.failure("得分不存在");
    }

    /**
     * 获取问卷平均分
     */
    @GetMapping("/score/average/{questionnaireId}")
    public Result getAverageScore(@PathVariable int questionnaireId) {
        Double avgScore = questionnaireService.getQuestionnaireAverageScore(questionnaireId);
        return avgScore != null ? ReturnResultUtil.success(avgScore) :
                ReturnResultUtil.failure("暂无统计结果");
    }

    /**
     * 检查用户是否完成问卷
     */
    @GetMapping("/completion/{questionnaireId}/{userId}")
    public Result checkCompletion(
            @PathVariable int questionnaireId,
            @PathVariable String userId) {
        boolean completed = questionnaireService.hasUserCompletedQuestionnaire(questionnaireId, userId);
        return ReturnResultUtil.success(completed);
    }

    /**
     * 获取用户完成的问卷数量
     */
    @GetMapping("/count/user/{userId}")
    public Result countUserQuestionnaires(@PathVariable String userId) {
        int count = questionnaireService.countUserCompletedQuestionnaires(userId);
        return ReturnResultUtil.success(count);
    }
}